package com.cangshi.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.cangshi.entity.JSONException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局抛错处理，返回json信息
 * Created by Eoly on 2017/3/28.
 */
public class JSONExceptionHandler extends SimpleMappingExceptionResolver {
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();

        FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();

        Integer error = null;

        if(ex instanceof JSONException) {
            error = ((JSONException) ex).getError();
        }

        if(error==null){
            error = -1;
        }

        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("error", error);
        attributes.put("msg", ex.getMessage());

        fastJsonJsonView.setAttributesMap(attributes);

        mv.setView(fastJsonJsonView);

        return mv;
    }
}
